<?php
class RebuildPlacementTree extends BuildTask {
    
    protected $title = 'Rebuild Placement Tree';
    
    protected $description = 'Rebuild Placement Tree';
    
    function init() {
        parent::init();
        $canAccess = (Director::isDev() || Director::is_cli() || Permission::check("ADMIN"));
        if(!$canAccess) return Security::permissionFailure($this);
    }
    
    public function run($request)
    {
        set_time_limit(0);
        $time = microtime();
        $time = explode(' ', $time);
        $time = $time[1] + $time[0];
        $start = $time;
        
		DB::alteration_message('Start rebuild placement tree', 'created');
		
        DB::query("update Placement set NLeft = 0, NRight = 0, NLevel = 0");
        $root_id = Distributor::get_id_by_username(Placement::get_root_username());
        $root = DataObject::get_one('Placement', "MemberID = ".(int)$root_id);
        $root->create_preorderings();
        
        $result1 = DB::query("select b.Username from Placement a inner join Member b on a.MemberID = b.ID where a.NLeft = 0 OR a.NRight = 0 OR a.NLevel = 0");
		
		$result2 = DB::query(sprintf("SELECT count(*) as total, b.ID FROM Placement a INNER JOIN Placement b on a.ParentID = b.ID GROUP BY b.ID HAVING total > %s", Placement::get_direct_child_limit()));
        
        if(sizeof($result1)){
            foreach($result1 as $data){
                DB::alteration_message(sprintf('Error rebuild placement tree (%s)', $data['Username']), 'deleted');
            }
        }
		else if($result2){
			foreach($result1 as $data){
                DB::alteration_message(sprintf('Error placement tree maximum node %s (%s)', $data['total'], Distributor::get_username_by_id($data['ID'])), 'deleted');
            }
		}
        else{
			DB::alteration_message('Finish rebuild placement tree', 'created');
        }
        
        $time = microtime();
        $time = explode(' ', $time);
        $time = $time[1] + $time[0];
        $finish = $time;
        $total_time = round(($finish - $start), 4);
        DB::alteration_message('Process Time - ' . $total_time . ' seconds', 'created');
    }
}

?>